<?php
namespace app\service\marketVideo;

use think\facade\Db;
use app\service\TopviewApiService;
use app\service\PointsService;

class M2vService
{
    protected $apiService;
    protected $pointsService;

    public function __construct()
    {
        $this->apiService = new TopviewApiService();
        $this->pointsService = new PointsService();
    }

    /**
     * 创建M2V任务
     * @param int $userId 用户ID
     * @param array $params 任务参数
     * @return array
     * @throws \Exception
     */
    public function createTask($userId, array $params)
    {
        // 验证必填参数
        if (empty($params['productLink']) && empty($params['fileIds'])) {
            throw new \Exception('产品链接和素材文件ID不能同时为空');
        }

        if (empty($params['productLink'])) {
            if (empty($params['productName'])) {
                throw new \Exception('产品名称不能为空');
            }
            if (empty($params['productDescription'])) {
                throw new \Exception('产品描述不能为空');
            }
        }

        // 从配置文件读取积分消耗
        $needPoints = config('points.points.m2v.points');

        // 检查用户积分
        $userPoints = $this->pointsService->getUserPoints($userId);
        if ($userPoints < $needPoints) {
            throw new \Exception("积分不足，需要{$needPoints}积分，当前余额{$userPoints}积分");
        }

        Db::startTrans();
        try {
            // 扣除积分
            $this->pointsService->consume($userId, $needPoints, '混剪视频生成');

            // 调用API提交任务
            $params['language'] = 'zh-CN';
            $result = $this->apiService->submitM2vTask($params);

            // 创建任务记录
            $taskData = [
                'user_id' => $userId,
                'task_id' => $result['taskId'],
                'product_link' => $params['productLink'] ?? '',
                'product_name' => $params['productName'] ?? '',
                'product_description' => $params['productDescription'] ?? '',
                'aspect_ratio' => $params['aspectRatio'] ?? '9:16',
                'language' => 'zh-CN',  // 写死为中文
                'voice_id' => $params['voiceId'] ?? '',
                'aiavatar_id' => $params['aiavatarId'] ?? '',
                'status' => 1, // 处理中
                'points_consumed' => $needPoints,
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s')
            ];

            if (!empty($params['fileIds'])) {
                $taskData['file_ids'] = json_encode($params['fileIds']);
            }

            $taskId = Db::name('m2v_tasks')->insertGetId($taskData);

            Db::commit();

            return [
                'task_id' => $taskId,
                'remote_task_id' => $result['taskId'],
                'consumed_points' => $needPoints
            ];

        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }

    /**
     * 查询任务状态
     * @param int $userId 用户ID
     * @param int $taskId 任务ID
     * @return array
     * @throws \Exception
     */
    public function queryTask($userId, $taskId)
    {
        // 获取任务信息
        $task = Db::name('m2v_tasks')
            ->where('id', $taskId)
            ->where('user_id', $userId)
            ->find();

        if (!$task) {
            throw new \Exception('任务不存在');
        }

        // 如果任务未完成，查询远程任务状态
        if ($task['status'] != 2) {
            $result = $this->apiService->queryM2vTask($task['task_id']);

            // 更新任务状态
            $updateData = [
                'status' => $this->convertStatus($result['status']),
                'update_time' => date('Y-m-d H:i:s')
            ];

            // 如果任务完成，保存视频地址
            if ($result['status'] === 'completed') {
                $updateData['video_url'] = $result['videoUrl'] ?? '';
            }

            // 如果任务失败，保存错误信息
            if ($result['status'] === 'failed') {
                $updateData['error_msg'] = $result['errorMsg'] ?? '生成失败';
            }

            Db::name('m2v_tasks')
                ->where('id', $taskId)
                ->update($updateData);

            $task = array_merge($task, $updateData);
        }

        return $task;
    }

    /**
     * 获取任务列表
     * @param int $userId 用户ID
     * @param int $page 页码
     * @param int $pageSize 每页数量
     * @return array
     */
    public function getTaskList($userId, $page = 1, $pageSize = 10)
    {
        $list = Db::name('m2v_tasks')
            ->where('user_id', $userId)
            ->order('create_time', 'desc')
            ->page($page, $pageSize)
            ->select()
            ->toArray();

        $total = Db::name('m2v_tasks')
            ->where('user_id', $userId)
            ->count();

        return [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'page_size' => $pageSize
        ];
    }

    /**
     * 转换状态
     * @param string $status 远程任务状态
     * @return int
     */
    private function convertStatus($status)
    {
        $statusMap = [
            'pending' => 0,    // 待处理
            'processing' => 1, // 处理中
            'completed' => 2,  // 已完成
            'failed' => 3      // 失败
        ];
        return $statusMap[$status] ?? 0;
    }
} 